/**
 * 
 */
package cn.com.gzheroli.core.util.docx4j;

import java.util.HashMap;

import org.docx4j.XmlUtils;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

/**  
* @类名: VariableReplace  
* @描述: TODO(这里用一句话描述这个类的作用)  
* @作者: 李长荣 lichang_20011@163.com  
* @日期: 2017年5月21日  上午8:17:31
*@version V1.0  
*    
*/
public class VariableReplace {
public static void main(String[] args) throws Exception {
		
		// Exclude context init from timing
		org.docx4j.wml.ObjectFactory foo = Context.getWmlObjectFactory();

		// Input docx has variables in it: ${colour}, ${icecream}
		String inputfilepath =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/test.docx";
		inputfilepath="g:/test.docx";
		boolean save = false;
		String outputfilepath =  "/Users/lichangrong/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/hoa/template/OUT_VariableReplace.docx";
		outputfilepath="g:/outtest.docx";
		WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
				.load(new java.io.File(inputfilepath));
		MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

		HashMap<String, Object> mappings = new HashMap<String, Object>();
		mappings.put("colour", "green李长荣");
		mappings.put("icecream", "chocolate测试");
		mappings.put("ttt", "lichangrong李长荣");
		mappings.put("ddd", "ceshi测试");
		mappings.put("李长荣", "lichangrong");
		mappings.put("测试", "ceshi");
		long start = System.currentTimeMillis();

		// Approach 1 (from 3.0.0; faster if you haven't yet caused unmarshalling to occur):
		
			documentPart.variableReplace(mappings);
		
/*		// Approach 2 (original)
		
			// unmarshallFromTemplate requires string input
			String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(), true);
			// Do it...
			Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);
			// Inject result into docx
			documentPart.setJaxbElement((Document) obj);
*/
			
		long end = System.currentTimeMillis();
		long total = end - start;
		System.out.println("Time: " + total);

		// Save it
		if (save) {
			SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
			saver.save(outputfilepath);
		} else {
			System.out.println(XmlUtils.marshaltoString(documentPart.getJaxbElement(), true,
					true));
		}
	}
}
